package deftoolbar

import (
	"yunj/pkg/yunj/app/service/admin/adminservice"
	"yunj/pkg/yunj/core/builder/builderaction"
	"yunj/pkg/yunj/core/builder/builderdto"
)

// 数据导出
type Export struct {
	Action
	// 如果有设置url，则优先使用设置url进行数据请求，反之请求当前构建器的数据
	Fields []builderdto.TableExportField `json:"fields"` // 导出字段
}

func NewExport(title ...string) *Export {
	a := &Export{}
	builderaction.SetActionInstance(&a.Action.Action, a)
	a.SetActionCode("export")
	if len(title) > 0 {
		a.SetTitle(title[0])
	}
	return a
}

// 设置标题
func (a *Export) SetTitle(title string) *Export {
	a.Title = title
	return a
}

// 设置额外的class或图标类名
func (a *Export) SetClass(class string) *Export {
	a.Class = class
	return a
}

// 设置导出字段
func (a *Export) SetFields(fields []builderdto.TableExportField) *Export {
	a.Fields = fields
	return a
}

// 设置权限
func (a *Export) SetAuth(auth string) *Export {
	a.Auth = auth
	return a
}

// 处理属性
func (a *Export) HandleAttr() error {
	// 设置默认值
	if a.Title == "" {
		a.Title = "数据导出"
	}
	if a.Class == "" {
		a.Class = "layui-icon-export"
	}
	// 字段
	if len(a.Fields) > 0 {
		fields := make([]builderdto.TableExportField, 0, len(a.Fields))
		var hasAuth bool
		for _, field := range a.Fields {
			// 判断权限
			hasAuth = adminservice.CheckAuth(a.GinContext, field.Auth)
			if !hasAuth {
				continue
			}
			fields = append(fields, field)
		}
		a.Fields = fields
	}
	return nil
}
